package whereRU.frontEnd;

import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

/**
 * This class manages the setting and cancelling of alarms for courses
 */
public class CourseAlarmManager {
	
	Context context;
	AlarmManager alarmManager;
	
	public final static String EXTRA_COURSE_DAYS = "sp.whereru.COURSE_DAYS";
	public final static String EXTRA_COURSE_NAME = "sp.whereru.COURSE_NAME";
	public final static String EXTRA_COURSE_ID = "sp.whereru.COURSE_ID";
	public final static String EXTRA_COURSE_ALARM_DELAY = "sp.whereru.COURSE_ALARM_DELAY";
	
	/**
	 * Constructor
	 * @param context the context of this alarm manager
	 */
	public CourseAlarmManager(Context context) {
		this.context = context;
		this.alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	}
	
	/**
	 * Sets an alarm to occur at the course start time
	 * @param course	the course to have an alarm set for
	 */
	public void setAlarm(Course course) {
		Calendar rightNow =  Calendar.getInstance();
		Calendar courseTime = (Calendar) rightNow.clone();
		int alarmId = (int) course.getId();
		
		courseTime.set(Calendar.HOUR_OF_DAY, course.getStartTime().getHours());
		courseTime.set(Calendar.MINUTE, course.getStartTime().getMinutes() - course.getAlarmDelay());
		
		// set the alarm to start repeating tomorrow at this time
		// if the current time is after the course time
		// or else the alarm will go off immediately after setting it
		if(rightNow.after(courseTime))
			courseTime.add(Calendar.DAY_OF_MONTH, 1);
		courseTime.set(Calendar.SECOND, 0);
		long when = courseTime.getTimeInMillis();
		
		Intent intent = new Intent(context, ReminderService.class);
		intent.putExtra(EXTRA_COURSE_NAME, course.getName());
		intent.putExtra(EXTRA_COURSE_DAYS, course.getDays());
		intent.putExtra(EXTRA_COURSE_ID, course.getId());
		intent.putExtra(EXTRA_COURSE_ALARM_DELAY, course.getAlarmDelay());
		PendingIntent pendingIntent = PendingIntent.getService(context, alarmId, intent, 0);
		
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when, AlarmManager.INTERVAL_DAY, pendingIntent);
	}
	
	/**
	 * Cancels an alarm for a given course id
	 * @param courseId	the course id
	 */
	public void cancelAlarm(long courseId) {
		Intent intent = new Intent(context, ReminderService.class);
		
		PendingIntent pendingIntent = PendingIntent.getService(context, (int) courseId, intent, 0);
		alarmManager.cancel(pendingIntent);
		// cancel the pending intent associated with this alarm
		pendingIntent.cancel();
	}	
}
